package com.example.lenovo.ruidaoproject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import static com.android.volley.VolleyLog.TAG;

public class LoginActivity extends AppCompatActivity {

    public static volatile String localCookie = null;
    RequestQueue requestQueue=null;
    EditText username,pwd,imgCode;
    ImageView img;
    private String url="http://www.neuedu.cn/m/mobileLogin!loginNeu.action";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logined);
        username=(EditText)findViewById(R.id.user);
        pwd=(EditText)findViewById(R.id.passWord);
        imgCode=(EditText)findViewById(R.id.imgCode);
        img=(ImageView)findViewById(R.id.img);
        requestQueue= Volley.newRequestQueue(this);

        String urlImg="http://www.neuedu.cn/imgcode";
        ImageRequest imageRequest=new ImageRequest(urlImg, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap bitmap) {
                img.setImageBitmap(bitmap);
            }
        }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                img.setImageResource(R.drawable.error);
            }
        }){
            @Override
            protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
                Response<Bitmap> superResponse = super
                        .parseNetworkResponse(response);
                Map<String, String> responseHeaders = response.headers;
                String rawCookies = responseHeaders.get("Set-Cookie");
                localCookie = rawCookies.substring(0, rawCookies.indexOf(";"));
                return superResponse;
            }
        };

        requestQueue.add(imageRequest);
    }
    public void login(View view){
        Map<String, String> map = new HashMap<String, String>();

        map.put("username", username.getText().toString());
        map.put("pwd",pwd.getText().toString());
        map.put("imgcode",imgCode.getText().toString());
        Request<JSONObject> request = new NormalPostRequest(url,

                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            //jsonObject1=new JSONObject(jsonObject.toString());
                            JSONObject jsonGet=response.getJSONObject("loginReturn");
                            int result=jsonGet.getInt("loginFlag");
                            System.out.println(result);

                            String errorMsg=jsonGet.getString("msg");
                            System.out.println(errorMsg);
                            if(result==1){
                                Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                                startActivity(intent);
                            }else {
                                new AlertDialog.Builder(LoginActivity.this)
                                        .setMessage(errorMsg)
                                        .setPositiveButton("OK",  new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        })
                                        .create()
                                        .show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }, map);
        requestQueue.add(request);
    }
    private class NormalPostRequest extends Request<JSONObject> {

        private Map<String, String> mMap;
        private Response.Listener<JSONObject> mListener;
        public NormalPostRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, Map<String, String> map) {
            super(Request.Method.POST, url, errorListener);
            mListener = listener;
            mMap = map;
        }
        //mMap是已经按照前面的方式,设置了参数的实例
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            return mMap;
        }
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            if (localCookie != null && localCookie.length() > 0) {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("cookie", localCookie);
                Log.d(TAG, "!!!!!!!!!!!!!" + headers);
                return headers;
            } else {
                return super.getHeaders();
            }
        }
        //此处因为response返回值需要json数据,和JsonObjectRequest类一样即可
        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException je) {
                return Response.error(new ParseError(je));
            }
        }


        @Override
        protected void deliverResponse(JSONObject response) {
            mListener.onResponse(response);
        }
    }
}
